package com.mandala.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

import com.mandala.entry.User;



public class StringUtil {
    //list去重复
    public   static  List<String>  removeDuplicate(List<String> list)  {       
    	  for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {       
    	      for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {       
    	           if  (list.get(j).equals(list.get(i)))  {       
    	              list.remove(j);       
    	            }        
    	        }        
    	      }        
    	    return list;       
    	}  
   
    // 删除ArrayList中重复元素，保持顺序     
    public static List<String>  removeDuplicateWithOrder(List<String> list) {    
       Set set = new HashSet();    
        List newList = new ArrayList();    
      for (Iterator iter = list.iterator(); iter.hasNext();) {    
            Object element = iter.next();    
            if (set.add(element))    
               newList.add(element);    
         }     
        list.clear();    
        list.addAll(newList);   
        return list;
    }   
    
    public static List<String> removeDuplicate3(List<String> list){  
    	List<String> listTemp = new ArrayList<>();  
        for(int i=0;i<list.size();i++){  
            if(!listTemp.contains(list.get(i))){  
                listTemp.add(list.get(i));  
            }  
        }  
        return listTemp;  
    }
    
    //根据list实体去重复
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    

    
    public static void main(String[] args) {
    	
    	List<String> name = new ArrayList();
    	User user = new User();
    	user.setCn("1");
    	User user2 = new User();
    	user2.setCn("2");
    	User user3 = new User();
    	user3.setCn("2");
    	List<User> listUser = new ArrayList<>();
    	listUser.add(user);
    	listUser.add(user2);
    	listUser.add(user3);
    	System.out.println("11==="+listUser.toString());
    	
    	List<User> personList = new ArrayList<>();
    	listUser.stream().filter(distinctByKey(p -> p.getCn())).forEach(p -> personList.add(p));
    	System.out.println("222=="+listUser.toString());
    	
       
        System.out.println(personList);
    	System.out.println("3=="+personList.toString());
    	

    	name.add("xxx");

    	name.add("yyy");

    	name.add("zzz");
    	
    	name.add("xxx");
    	System.out.println(name);
    	System.out.println(removeDuplicate3(name));;
    	
    }
}
